// pages/cart/cart.js
let app = getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        primary: app.globalData.primary, // 主题色
        ossPath: app.globalData.ossPath,
        checked: true,
        cartList: [], // 购物车
        myCart: { // 购物车数据
            'InvoiceID': 0,
            'AddressID': 0,
            'ShippingTypeID': 1,
            'CouponCode': '',
            ShoppingCartItem: [],
        },
        selectAllBtn: false, // 全选按钮
        totalPrice: 0, // 结算价格
        firstScreen: true, // 骨架
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        //设置主题色
        if (app.globalData.primary) {
            this.setData({ primary: app.globalData.primary })
            app.usePrimary(app.globalData.primary)
        }

    },
    getCartList:function() {// 获取购物车信息
        wx.showLoading({
            title: '加载中'
        })
        if (!this.data.myCart.ShoppingCartItem.length) {
            wx.hideLoading()
            return
        }
        this.setData({
            firstScreen: true
        })
        var params = this.data.myCart;
        wx.request({
            url: app.globalData.serverPath + '/ShoppingCar',
            method: 'post',
            header: {token: app.globalData.header.token},
            data: params,
            success: ({data}) => {
                let list = [];
                let t = true;
                this.data.totalPrice = 0
                data.ShoppingCartItem.forEach((item, i) => {
                    let AttributeList = '', CraftList = "";
                    item.AttributeList.forEach(attr => { // 遍历所有的材质属性
                        attr.Items.forEach(t => {
                            AttributeList += ' ' + t.Name // 拼接所有的材质
                        })
                    })
                    item.CraftList.forEach(c => {// 遍历所有的工艺属性
                        CraftList += ' ' + c.Name
                    })
                    console.log(item)
                    list.push({
                        Name: item.PriceSheet.Name,
                        AttributeList: AttributeList,
                        CraftList: CraftList,
                        Count: item.Quantitys[0].Number + item.ProductType.Unit,
                        TotalPrice: item.TotalPrice ,
                        Urgent: item.Urgent,
                        ImageUrl: item.Thumb || item.ProductType.ImageUrl,
                        Selected: this.data.myCart.ShoppingCartItem[i].Selected,
                        touchBtn: false
                    })
                    if (this.data.myCart.ShoppingCartItem[i].Selected) this.data.totalPrice += item.TotalPrice;
                    else t = false
                })
                this.data.selectAllBtn = t;
                this.data.myCart.ShoppingCartItem = list
                this.setData({
                    selectAllBtn: this.data.selectAllBtn,
                    totalPrice: this.data.totalPrice,
                    myCart: this.data.myCart,
                    firstScreen: false
                })
            },
            complete: () => wx.hideLoading()
        })
    },
    changeSelect(event) { //单选改变
        var index = event.currentTarget.dataset.index;
        this.data.myCart.ShoppingCartItem[index].Selected = !this.data.myCart.ShoppingCartItem[index].Selected
        let t = true;
        this.data.totalPrice = 0;
        for (let key in this.data.myCart.ShoppingCartItem) {
            if (!this.data.myCart.ShoppingCartItem[key].Selected) {
                t = false;
            } else {
                this.data.totalPrice += this.data.myCart.ShoppingCartItem[key].TotalPrice
            }
        }
        this.putCart(index, this.data.myCart.ShoppingCartItem[index].Selected ? 1 : 0 )
        this.data.selectAllBtn = t;
        this.setData({
            selectAllBtn: this.data.selectAllBtn,
            totalPrice: this.data.totalPrice,
            myCart: this.data.myCart
        });

      },
    selectAll() { // 全选
        this.data.selectAllBtn = !this.data.selectAllBtn;
        this.data.totalPrice = 0;
        this.data.myCart.ShoppingCartItem.forEach((item, i) => {
            item.Selected = this.data.selectAllBtn ? 1 : 0;
            this.data.totalPrice += item.TotalPrice
            this.putCart( i, item.Selected)
        })
        this.data.totalPrice = this.data.selectAllBtn ? this.data.totalPrice : 0
        this.setData({
            myCart: this.data.myCart,
            totalPrice: this.data.totalPrice,
            selectAllBtn: this.data.selectAllBtn
        })
    },
    onClickButton: function() { // 提交订单
        app.checkedUserInfo().then(data => {
            if (data) {
                if (!this.data.totalPrice) return
                wx.navigateTo({
                    url: '../submit_order/submit_order'
                })
            }
        })
    },
    putCart: function(i, type) { // 修改本地存储的购物车
        if (!this.data.cartList.length) return;
        this.data.cartList[i].Selected = type;
        this.setData({
            cartList: this.data.cartList
        })
        var json = JSON.stringify(this.data.cartList);
        wx.setStorageSync('cart', json)
    },
    deleteCart: function(i) { // 删除购物车商品
        if (!this.data.cartList.length) return;
        this.data.cartList.splice(i, 1);
        this.setData({
            cartList: this.data.cartList
        })
        var json = JSON.stringify(this.data.cartList);
        wx.setStorageSync('cart', json)

        app.setCartbadge();
    },
    handleDelete: function(e) {//删除
        var index = e.currentTarget.dataset.index;
        this.data.myCart.ShoppingCartItem.splice(index, 1);
        this.data.totalPrice = 0;
        this.data.myCart.ShoppingCartItem.forEach((item, i) => {
            this.data.totalPrice += item.TotalPrice
        })
        this.setData({
            myCart: this.data.myCart,
            totalPrice: this.data.totalPrice
        })
        this.deleteCart(index)
        
    },
    gotoPrint: function() {
        wx.switchTab({
            url: '../print/print'
        })
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

        var cart = wx.getStorageSync('cart')
        try {
            cart = JSON.parse(cart)
        } catch (e) {
            cart = []
        }
        this.data.myCart.ShoppingCartItem = cart;
        this.setData({ myCart: this.data.myCart, cartList: cart })
        this.getCartList();
        app.setCartbadge();
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {
        alert('下拉')
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})